package cn.cloudreal.cbms.project.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.ibatis.sqlmap.client.SqlMapClient;

import cn.cloudreal.cbms.common.exception.ITCException;
import cn.cloudreal.cbms.common.util.Constants;
import cn.cloudreal.cbms.common.util.DatadicContext;
import cn.cloudreal.cbms.common.util.PageBean;
import cn.cloudreal.cbms.project.dao.ProjectDao;
import cn.cloudreal.cbms.vo.CastForProj;
import cn.cloudreal.cbms.vo.Dictionary;
import cn.cloudreal.cbms.vo.Project;

public class ProjectDaoImpl implements ProjectDao
{
    private static final Logger log = Logger.getLogger(ProjectDaoImpl.class);

    private SqlMapClient sqlMapClient;

    public SqlMapClient getSqlMapClient()
    {
        return sqlMapClient;
    }

    public void setSqlMapClient(SqlMapClient sqlMapClient)
    {
        this.sqlMapClient = sqlMapClient;
    }

    /**
     * @category 新增项目信息
     * @throws SQLException
     * @param project
     *            Project
     * @return Boolean
     */
    public boolean addProject(Project project)
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl addProjectInfo() method,return boolean");
        }

        try
        {
            sqlMapClient.insert("Project.addProjectInfo", project);
        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl addProjectInfo() method,return boolean",
                    e);
            throw new ITCException("301", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl addProjectInfo() method,return boolean");
        }
        return true;
    }

    /**
     * @throws SQLException
     * @category 修改项目信息
     * @param project
     *            Project
     * @return Boolean
     */
    public boolean modProject(Project project)
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl modProject() method,return boolean");
        }
        try
        {
            sqlMapClient.update("Project.modProjectInfo", project);
        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl modProject() method,return boolean",
                    e);
            throw new ITCException("302", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl modProject() method,return boolean");
        }
        return true;
    }

    /**
     * @throws SQLException
     * @category 删除项目信息
     * @param projectId
     *            String
     * @return Boolean
     */
    public boolean delProject(String projectId)
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl delProject() method,return boolean");
        }

        try
        {
            sqlMapClient.delete("Project.delProjectInfo", projectId);
        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl delProject() method,return boolean",
                    e);
            throw new ITCException("303", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl delProject() method,return boolean");
        }
        return true;

    }

    /**
     * @throws SQLException
     * @category 查询项目列表数据
     * @param params
     *            Map<String, Object> ,page PageBean
     * @return List<Project>
     * @exception
     */
    public List<Project> getProjectList(Map<String, Object> params,
            PageBean page)
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl getProjectList() method,return List<Project>");
        }

        List<Project> plist = null;
        try
        {
            if (null != page)
            {
                int totalCount = (Integer) sqlMapClient.queryForObject("Project.getProjectCount",
                        params);
                page.setTotalRecords(totalCount);
                if (totalCount == 0)
                {
                    return null;
                }
                params.put("pageNo", page.getPageNo());
                params.put("pageSize", page.getPageSize());

                plist = (List<Project>) sqlMapClient.queryForList("Project.getProjectList",
                        params);
            }
            else
            {
                plist = (List<Project>) sqlMapClient.queryForList("Project.getProjectListNoPage",
                        params);
            }

        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl getProjectList() method,return List<Project>",
                    e);
            throw new ITCException("304", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl getProjectList() method,return boolean");
        }
        return plist;
    }

    /**
     * @throws SQLException
     * @category 获取项目下相关信息
     * @param project
     *            Project
     * @return Map<String,Object>
     * @exception e
     */
    public Project getProjectRelateInfo(Map<String, Object> params)
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl getProjectRelateInfo() method,return Project");
        }
        Project pro = null;
        try
        {
            pro = (Project) sqlMapClient.queryForObject("Project.getProjectInfo",
                    params);
        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl getProjectRelateInfo() method,return Project",
                    e);
            throw new ITCException("305", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl getProjectRelateInfo() method,return boolean");
        }
        return pro;
    }

    /**
     * @throws SQLException
     * @category 判断项目下是否有媒介信息
     * @param projectId
     *            String
     * @return boolean
     * @exception e
     */
    public boolean isMediumExist(String projectId)
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl isMediumExist() method,return boolean");
        }
        try
        {
            // 项目下排期信息已存在
            int num = ((Integer) sqlMapClient.queryForObject("Project.getMediumInProj",
                    projectId)).intValue();
            if (num > 0)
            {
                log.info("Project has Medium in use! projectId: " + projectId);
                return true;
            }
        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl isMediumExist() method,return boolean",
                    e);
            throw new ITCException("306", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl isMediumExist() method,return boolean");
        }
        return false;
    }

    /**
     * @throws SQLException
     * @category 判断项目信息是否已经存在
     * @param params
     *            Map<String,Object>
     * @return boolean
     * @exception SQLException
     */
    public boolean isProjectExist(Map<String, Object> params)
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl isProjectExist() method,return boolean");
        }
        try
        {
            // 项目已经存在
            int num = ((Integer) sqlMapClient.queryForObject("Project.isProjExist",
                    params)).intValue();

            if (num > 0)
            {
                log.info("Project is Exist!");
                return true;
            }

        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl isProjectExist() method,return boolean",
                    e);
            throw new ITCException("307", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl isProjectExist() method,return boolean");
        }
        return false;
    }
    

    public String getProjCurStatus(String projectId) throws ITCException
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl getProjCurStatus() method,return String");
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("projectId", projectId);
        List<String> statusList = null;
        String status = null;
        try
        {
            statusList = (List<String>) sqlMapClient.queryForList("Project.getCastCurStatus",
                    params);
            if(null!=statusList && statusList.size()>0)
            {
                status = statusList.get(0);
            }
            //status = statusList.get(0);
        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl getProjCurStatus() method,return String",
                    e);
            throw new ITCException("314", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl getProjCurStatus() method,return String");
        }
        return status;
    }

    public Map<String, Integer> getCastCountByProjId(String projectId,String curStatus)
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl getCastCountByProjId() method,return Map<String, Integer>");
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("projectId", projectId);
        Integer countCur = 0;
        Integer hiscount = 0;
        Map<String, Integer> countMap = new HashMap<String, Integer>();
        try
        {
            if(!"".equals(curStatus))
            {
                countCur = (Integer) sqlMapClient.queryForObject("Project.getCastCurrentCount",
                        params);
                countMap.put(curStatus, countCur);
                // 查询项目历史状态的个数
                List<Dictionary> dics = DatadicContext.getInstance()
                        .getDicDataListByCode(Constants.MEDIUM_STATE_CODE);
                List<Dictionary> status = new ArrayList<Dictionary>();

                    for (int m = 0; m < dics.size(); m++)
                    {
                        if (!dics.get(m).getId().equals(curStatus))
                        {
                            status.add(dics.get(m));
                        }
                    }
                    for (int n = 0; n < status.size(); n++)
                    {
                        params.remove("mediumStatus");
                        params.put("mediumStatus", status.get(n).getId());
                        hiscount = (Integer) sqlMapClient.queryForObject("Project.getCastHistoryCount",
                                params);
                        countMap.put(status.get(n).getId(), hiscount);
                    }
            }
            else
            {
                // 查询项目历史状态的个数
                List<Dictionary> dics = DatadicContext.getInstance()
                        .getDicDataListByCode(Constants.MEDIUM_STATE_CODE);
                for (int n = 0; n < dics.size(); n++)
                {
                    params.remove("mediumStatus");
                    params.put("mediumStatus", dics.get(n).getId());
                    hiscount = (Integer) sqlMapClient.queryForObject("Project.getCastHistoryCount",
                            params);
                    countMap.put(dics.get(n).getId(), hiscount);
                }
            }

        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl getCastCountByProjId() method,return Map<String, Integer>",
                    e);
            throw new ITCException("312", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl getCastCountByProjId() method,return Map<String, Integer>");
        }
        return countMap;
    }

    /**
     * @throws SQLException
     * @category 根据项目编号获取项目下相关投放明细信息
     * @param projectId
     *            String
     * @return castsList List<CastForProj>
     * @exception SQLException
     */
    public Map<String, List<CastForProj>> getCastByProjId(String projectId,String curStatus)
            throws ITCException
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl getCastByProjId() method,return Map<String, List<CastForProj>>");
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("projectId", projectId);
        List<CastForProj> castCurList = null;
        List<CastForProj> castHisList = null;
        Map<String, List<CastForProj>> resMap = new HashMap<String, List<CastForProj>>();
        try
        {
            if(!"".equals(curStatus))
            {
                // 查询项目当前状态的明细
                castCurList = (List<CastForProj>) sqlMapClient.queryForList("Project.getCastCurrentByProjID",
                        params);
                resMap.put(curStatus, castCurList);
                // 查询项目历史状态的明细
                List<Dictionary> dics = DatadicContext.getInstance()
                        .getDicDataListByCode(Constants.MEDIUM_STATE_CODE);
                List<Dictionary> status = new ArrayList<Dictionary>();
                for (int m = 0; m < dics.size(); m++)
                {
                    if (!dics.get(m).getId().equals(curStatus))
                    {
                        status.add(dics.get(m));
                    }
                }
                for (int n = 0; n < status.size(); n++)
                {
                    params.remove("mediumStatus");
                    params.put("mediumStatus", status.get(n).getId());
                    castHisList = (List<CastForProj>) sqlMapClient.queryForList("Project.getCastHistoryByProjID",
                            params);
                    resMap.put(status.get(n).getId(), castHisList);
                }
            }
            else
            {
                // 查询项目历史状态的明细
                List<Dictionary> dics = DatadicContext.getInstance()
                        .getDicDataListByCode(Constants.MEDIUM_STATE_CODE);
                for (int n = 0; n < dics.size(); n++)
                {
                    params.remove("mediumStatus");
                    params.put("mediumStatus", dics.get(n).getId());
                    castHisList = (List<CastForProj>) sqlMapClient.queryForList("Project.getCastHistoryByProjID",
                            params);
                    resMap.put(dics.get(n).getId(), castHisList);
                }
            }

        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl getCastByProjId() method,return Map<String, List<CastForProj>>",
                    e);
            throw new ITCException("313", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl getCastByProjId() method,return Map<String, List<CastForProj>>");
        }
        return resMap;
    }

    /**
     * @throws SQLException
     * @category 根据项目编号获取项目下相关排期信息
     * @param projectId
     *            String
     * @return arrageList List<CastForProj>
     * @exception SQLException
     */
    public List<CastForProj> getCastArrangeByProjId(String projectId)
            throws ITCException
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl getCastArrangeByProjId() method,return List<CastDetail>");
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("projectId", projectId);
        List<CastForProj> arrageList = null;
        try
        {
            arrageList = (List<CastForProj>) sqlMapClient.queryForList("Project.getCastArrangeByProjID",
                    params);
        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl getCastArrangeByProjId() method,return List<CastDetail>",
                    e);
            throw new ITCException("309", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl getCastArrangeByProjId() method,return List<CastDetail>");
        }
        return arrageList;
    }

    /**
     * @throws SQLException
     * @category 根据项目媒介编号删除投放明细信息
     * @param projMedId
     *            Integer
     * @return boolean
     * @exception ITCException
     */
    public boolean deleteCastInfo(Integer projMedId) throws ITCException
    {

        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl deleteCastInfo() method,return boolean");
        }
        try
        {
            sqlMapClient.delete("Project.delCastForProj", projMedId);
        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl deleteCastInfo() method,return boolean",
                    e);
            throw new ITCException("310", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl deleteCastInfo() method,return boolean");
        }
        return true;
    }

    /**
     * @throws SQLException
     * @category 根据项目媒介编号修改投放明细状态
     * @param proMedIds
     *            List<Integer>,status String
     * @return boolean
     * @exception ITCException
     */
    public boolean updateCastStatus(String status, List<Integer> proMedIds)
            throws ITCException
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl updateCastStatus() method,return boolean");
        }
        try
        {
            sqlMapClient.startTransaction();
            sqlMapClient.startBatch();
            Map<String, Object> params = new HashMap<String, Object>();
            for(int n = 0; n < proMedIds.size() ; n++)
            {
                params.put("newStatus", status);
                params.put("proMedId", proMedIds.get(n));
                sqlMapClient.update("Project.modCastStatus", params);
            }
            sqlMapClient.executeBatch();
        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl deleteCastInfo() method,return boolean",
                    e);
            throw new ITCException("311", e);
        }
        finally 
        {    
           try 
           {  
              // 结束事务  
              sqlMapClient.endTransaction();  
           } 
           catch (SQLException e) 
           {  
              e.printStackTrace();  
           }  
        }    
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl updateCastStatus() method,return boolean");
        }
        return true;
    }

    public Integer getAmountByCur(Map<String, Object> params)
            throws ITCException
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl getAmountByCur() method,return Integer");
        }
        Integer amount = 0;
        try
        {
            amount = (Integer)sqlMapClient.queryForObject("Project.getAmountByCur",params);
        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl getAmountByCur() method,return Integer",
                    e);
            throw new ITCException("311", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl getAmountByCur() method,return Integer");
        }
        return amount;
    }

    public Integer getAmountByHis(Map<String, Object> params)
            throws ITCException
    {
        if (log.isInfoEnabled())
        {
            log.info("Enter ProjectDaoImpl getAmountByHis() method,return Integer");
        }
        Integer amount = 0;
        try
        {
            amount = (Integer)sqlMapClient.queryForObject("Project.getAmountByHIS",params);
        }
        catch (SQLException e)
        {
            log.error("Error ProjectDaoImpl getAmountByHis() method,return Integer",
                    e);
            throw new ITCException("311", e);
        }
        if (log.isInfoEnabled())
        {
            log.info("Exit ProjectDaoImpl getAmountByHis() method,return Integer");
        }
        return amount;
    }


}
